package com.king.fast.server;

import com.king.fast.kit.PathKit;

/**
 * @author taomk
 * @version 1.0
 * @since 14-12-17 下午3:48
 */
public class ServerFactory {

	private static final int DEFAULT_PORT = 80;
	private static final int DEFAULT_SCANINTERVALSECONDS = 5;

	/**
	 * 返回一个Web容器
	 * <p>
	 * @param webAppDir webapp/webroot目录路径
	 * @param port 端口号
	 * @param context 应用名称
	 * @param scanIntervalSeconds 热部署间隔秒数，如果<1，则关闭热部署。
	 */
	public static IServer getServer(String webAppDir, int port, String context, int scanIntervalSeconds) {
		return new FastServer(webAppDir, port, context, scanIntervalSeconds);
	}

	public static IServer getServer(String webAppDir, int port, String context) {
		return getServer(webAppDir, port, context, DEFAULT_SCANINTERVALSECONDS);
	}

	public static IServer getServer(int port, String context, int scanIntervalSeconds) {
		return getServer(detectWebAppDir(), port, context, scanIntervalSeconds);
	}

	public static IServer getServer(int port, String context) {
		return getServer(detectWebAppDir(), port, context, DEFAULT_SCANINTERVALSECONDS);
	}

	public static IServer getServer(int port) {
		return getServer(detectWebAppDir(), port, "/", DEFAULT_SCANINTERVALSECONDS);
	}

	public static IServer getServer() {
		return getServer(detectWebAppDir(), DEFAULT_PORT, "/", DEFAULT_SCANINTERVALSECONDS);
	}

	private static String detectWebAppDir() {
		String rootClassPath = PathKit.getRootClassPath();
		String[] temp;
		if (rootClassPath.contains("\\WEB-INF\\"))
			temp = rootClassPath.split("\\\\");
		else if (rootClassPath.contains("/WEB-INF/"))
			temp = rootClassPath.split("/");
		else
			throw new RuntimeException("WEB-INF directory not found.");
		return temp[temp.length - 3];
	}
}
